/**
 * 个人中心页面JavaScript逻辑
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.NORMAL_USER)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

function normalizeAppointmentList(data) {
    if (!data) {
        return [];
    }
    if (Array.isArray(data)) {
        return data;
    }
    if (Array.isArray(data.records)) {
        return data.records;
    }
    return [];
}

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 加载统计数据
    await loadStatistics();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '用户';
        
        // 顶部导航栏
        document.getElementById('userName').textContent = userName;
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
        
        // 个人信息卡片
        document.getElementById('profileAccount').textContent = userName;
        document.getElementById('profileUserId').textContent = userInfo.userId || '-';
        document.getElementById('profileRole').textContent = Format.userRole(userInfo.identityInfo);
        
        const profileAvatar = document.getElementById('profileAvatar');
        profileAvatar.textContent = userName.charAt(0).toUpperCase();
    }
}

/**
 * 加载统计数据
 */
async function loadStatistics() {
    try {
        // 加载预约数据
        const appointmentPage = await HttpClient.get('/appointment/list');
        const appointments = normalizeAppointmentList(appointmentPage);
            document.getElementById('totalAppointments').textContent = appointments.length;
            
            // 统计各状态预约数
            const completed = appointments.filter(a => a.appointmentStatus === 1).length;
            const pending = appointments.filter(a => a.appointmentStatus === 0).length;
            
            document.getElementById('completedAppointments').textContent = completed;
            document.getElementById('pendingAppointments').textContent = pending;
        
        // 加载家属数据
        const families = await HttpClient.get('/family/list');
        if (families && Array.isArray(families)) {
            document.getElementById('totalFamily').textContent = families.length;
        }
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

/**
 * 处理修改密码
 */
async function handleChangePassword() {
    const oldPassword = document.getElementById('oldPassword').value.trim();
    const newPassword = document.getElementById('newPassword').value.trim();
    const confirmPassword = document.getElementById('confirmPassword').value.trim();
    
    // 表单验证
    if (!oldPassword) {
        UI.showMessage('请输入原密码', 'warning');
        return;
    }
    
    if (!newPassword) {
        UI.showMessage('请输入新密码', 'warning');
        return;
    }
    
    if (newPassword.length < 6) {
        UI.showMessage('新密码长度至少6位', 'warning');
        return;
    }
    
    if (!confirmPassword) {
        UI.showMessage('请确认新密码', 'warning');
        return;
    }
    
    if (newPassword !== confirmPassword) {
        UI.showMessage('两次输入的新密码不一致', 'warning');
        return;
    }
    
    if (oldPassword === newPassword) {
        UI.showMessage('新密码不能与原密码相同', 'warning');
        return;
    }
    
    try {
        const data = {
            oldPassword: oldPassword,
            newPassword: newPassword
        };
        
        await HttpClient.put('/user/password', data);
        
        UI.showMessage('修改密码成功，请重新登录', 'success');
        
        // 清空表单
        document.getElementById('changePasswordForm').reset();
        
        // 2秒后退出登录
        setTimeout(() => {
            Auth.logout();
        }, 2000);
    } catch (error) {
        console.error('修改密码失败:', error);
        UI.showMessage(error.message || '修改密码失败', 'danger');
    }
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

